import { Button, Spin, Drawer } from 'antd';
import ProTable from '@ant-design/pro-table';
import React, { useState } from 'react';
import type { ProColumns } from '@ant-design/pro-table';
import ProForm, { ProFormDatePicker, ProFormGroup, ProFormSelect } from '@ant-design/pro-form';
import request from '@/utils/request';
import { putOutFormList, hosSalesVolume, exportPutOutForm } from '../../pages/Statistics/service';
import { message } from 'antd';
import { exportFile, manufacturerOption } from '@/utils/utils';
import { Upload } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
export type PutOutProps = {
  outType: number;
};

const PutOut: React.FC<PutOutProps> = props => {
  const [showDetail, setShowDetail] = useState(false);
  const [chartDetail, setChartDetail] = useState(false);
  const [proData, setProData] = useState([]);
  const [subProData, setSubProData] = useState([]);
  const [cData, setCData] = useState([]);
  const [spinningFlag, setSpinningFlag] = useState(false);
  const [areas, setAreas] = useState<any[]>(); // const [detailData,setDetailData] = useState({});

  const [ticketAttList, setTicketAttList] = useState([]);

  async function requestAreas() {
    var val = await request('/xwyl/cm/region/getChinaData', {});
    setAreas(val.data);
  }

  function dealerJsonData() {
    return request('/xwyl/dealer/dealerJsonData');
  }

  function salesJsonData() {
    return request('/xwyl/salesTeam/salesJsonData');
  }

  async function requestPro() {
    var val = await request('/xwyl/product/productJsonData');
    val.forEach((item: any) => {
      item.children.forEach((sub: any) => {
        sub.value = sub.label;
      });
    });
    setProData(val);
  }

  async function requestCData(param: any) {
    param.state = props.outType;
    var val = await hosSalesVolume(param);
    val.forEach((element: any) => {
      element.value = Number(element.value);
    });
    setCData(val);
  }

  React.useEffect(() => {
    requestPro();
    requestCData({});
    requestAreas();
    return function cleanup() {};
  }, []); //表头信息以及表值设置

  const columns: ProColumns[] = [{
    title: '客户代码',
    dataIndex: 'dealerCode',
    width: 150,
    fixed: 'left'
  }, {
    title: '客户名称',
    dataIndex: 'dealerName',
    width: 300,
    fixed: 'left'
  }, {
    title: '客户等级',
    dataIndex: 'dealerLevel',
    width: 100,
    valueType: 'select',
    valueEnum: {
      一级: {
        text: '一级'
      },
      二级: {
        text: '二级'
      }
    }
  }, {
    title: '提交日期',
    dataIndex: 'createDate',
    hideInSearch: true,
    width: 150
  }, {
    title: '出库日期',
    dataIndex: 'putoutDate',
    hideInSearch: true,
    width: 150
  }, {
    title: '开票日期',
    dataIndex: 'billDate',
    hideInSearch: true,
    width: 150
  }, {
    title: '发票号码',
    dataIndex: 'billNo',
    hideInSearch: true,
    width: 150
  }, {
    title: '选择日期',
    valueType: 'dateRange',
    width: 100,
    dataIndex: 'date',
    hideInTable: true
  }, {
    title: props.outType == 1 ? '医院代码' : '客户代码',
    width: 150,
    dataIndex: 'receiverNo'
  }, {
    title: props.outType == 1 ? '医院名称' : '客户名称',
    width: 200,
    ellipsis: true,
    dataIndex: 'receiver'
  }, {
    title: '医院等级',
    width: 100,
    dataIndex: 'level',
    hideInSearch: true,
    renderText: (_, record) => {
      return record.level + record.grade;
    }
  }, {
    title: '销售金额',
    width: 100,
    valueType: 'money',
    dataIndex: 'originalPrice',
    hideInSearch: true
  }, {
    title: '销售',
    width: 120,
    dataIndex: 'salesName',
    hideInSearch: true
  }, {
    title: '一线管理',
    width: 120,
    dataIndex: 'leaderSalesName',
    hideInSearch: true
  }, {
    title: '二线管理',
    width: 120,
    dataIndex: 'superiorName',
    hideInSearch: true
  }, {
    title: '销售主要联系人',
    width: 120,
    dataIndex: 'liable',
    ellipsis: true,
    hideInSearch: true
  }, {
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    valueEnum: manufacturerOption(),
    width: 80
  }, {
    title: '产品名称',
    width: 200,
    dataIndex: 'productName'
  }, {
    width: 200,
    title: '产品型号',
    dataIndex: 'productStandard'
  }, {
    title: '单位',
    width: 50,
    dataIndex: 'packingUnit',
    ellipsis:true,
    hideInSearch: true,
    editable: false
  }, {
    width: 100,
    title: '批号',
    hideInSearch: true,
    dataIndex: 'batch'
  }, {
    width: 120,
    title: '失效日期',
    dataIndex: 'validity',
    hideInSearch: true
  }, {
    width: 100,
    title: '数量',
    dataIndex: 'numbs',
    hideInSearch: true
  }, {
    width: 100,
    title: '单价(元)',
    hideInSearch: true,
    valueType: 'money',
    dataIndex: 'standardPrice'
  }, {
    width: 100,
    title: '总价(元)',
    hideInSearch: true,
    valueType: 'money',
    dataIndex: 'originalPrice'
  }, {
    width: 100,
    title: '采购单价(元)',
    hideInSearch: true,
    valueType: 'money',
    dataIndex: 'purchaseUnPrice'
  }, {
    width: 100,
    title: '采购总价(元)',
    hideInSearch: true,
    valueType: 'money',
    dataIndex: 'purchasePrice'
  }, {
    title: '医院级别',
    width: 80,
    dataIndex: 'level',
    hideInTable: true
  }, {
    title: '医院评等',
    width: 80,
    dataIndex: 'grade',
    hideInTable: true
  }, {
    title: '操作',
    valueType: 'option',
    width: 100,
    render: (text, record: any, _, action) => [<a key='detail' hidden={!record.putoutFormId} onClick={async () => {
      setSpinningFlag(true);
      var param: any = {
        shipId: record.putoutFormId
      };
      var fileData = request('/xwyl/attachment/attachListData', {
        method: 'POST',
        requestType: 'form',
        data: { ...param
        }
      });
      var val = await fileData;

      if (val.errorCode = 200) {
        val.data.forEach((element: any) => {
          element.uid = element.id;
          element.name = element.attName;
          element.url = element.attPath;
          element.status = 'done';
        });
        setTicketAttList(val.data);
        setShowDetail(true);
      }

      setSpinningFlag(false);
    }} >
          发票
        </a>]
  }];
  var config = {
    data: cData,
    xField: 'name',
    yField: 'value',
    label: {
      position: 'middle',
      style: {
        fill: '#FFFFFF',
        opacity: 0.6
      }
    },
    meta: {
      type: {
        alias: '日期'
      },
      value: {
        alias: '销售额'
      }
    }
  };

  const handlePreview = async (file: any) => {
    window.open(file.url);
  };

  return <PageContainer>
        <ProTable headerTitle='销量列表' columns={columns} scroll={{
      x: 3000
    }} request={(params, sorter, filter) => {
      params.state = props.outType;

      if (params.date) {
        params.beginDate = params.date[0];
        params.endDate = params.date[1];
        params.date = undefined;
      }

      params.salesId = params.salesName;
      params.salesName = undefined;

      if (params.provinces_label) {
        if (params.provinces_label.length == 2) {
          params.city = params.provinces_label[1];
        }

        params.provinces = params.provinces_label[0];
        params.provinces_label = undefined;
      }

      return putOutFormList({ ...params,
        filter
      });
    }} rowKey='id' search={{
      span: 6,
      defaultCollapsed: false,
      collapseRender:false,
      optionRender: ({
        searchText,
        resetText
      }, {
        form
      }) => [<Button key='search' type='primary' onClick={() => {
        form?.submit();
      }} >
                {searchText}
              </Button>, <Button key='rest' onClick={() => {
        form?.resetFields();
        form?.submit();
      }} >
                {resetText}
              </Button>, <Button key='out' onClick={async () => {
        setSpinningFlag(true);
        var date = form?.getFieldValue('date');
        var params: any = {};

        if (date) {
          params.beginDate = date[0].format('YYYY-MM-DD');
          params.endDate = date[1].format('YYYY-MM-DD');
          params.date = undefined;
        }

        params.state = props.outType;
        params.salesId = form?.getFieldValue('salesName');
        params.dealerName = form?.getFieldValue('dealerName');
        params.dealerCode = form?.getFieldValue('dealerCode');
        params.receiver = form?.getFieldValue('receiver');
        params.receiverNo = form?.getFieldValue('receiverNo');
        params.productName = form?.getFieldValue('productName');
        params.productStandard = form?.getFieldValue('productStandard');
        params.dealerLevel = form?.getFieldValue('dealerLevel');
        var provinces_label = form?.getFieldValue('provinces_label');
        var city = '';
        var provinces = '';

        if (provinces_label) {
          if (provinces_label.length == 2) {
            city = provinces_label[1];
            params.city = city;
          }

          provinces = provinces_label[0];
          params.provinces = provinces;
        }

        params.manufacturer = form?.getFieldValue('manufacturer');
        params.level = form?.getFieldValue('level');
        params.grade = form?.getFieldValue('grade');
        var val = await exportPutOutForm(params);

        if (val.errorCode === '200') {
          exportFile(val.data, props.outType == 1 ? '医院销量.xlsx' : '客户销量.xlsx');
        } else {
          message.error(val.errorMessage);
        }

        setSpinningFlag(false);
      }} >导出</Button>]
    }} toolBarRender={() => [// <Button
      //   type=primary
      //   key=primary
      //   onClick={() => {
      //     setChartDetail(true);
      //   }}
      // ><AreaChartOutlined />图表</Button>
    ]} toolbar={{
      settings: []
    }} pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} />
        <Drawer width={1000} title='详情' visible={showDetail} onClose={() => setShowDetail(false)} destroyOnClose={true} >
               <Upload fileList={ticketAttList} onPreview={handlePreview} showUploadList={{
        showRemoveIcon: false
      }} >
              </Upload>
          </Drawer>
        <Drawer width={1010} title='图表' visible={chartDetail} onClose={() => setChartDetail(false)} destroyOnClose={true}>
              <ProForm style={{
        position: 'relative',
        marginBottom: 40
      }} submitter={{
        searchConfig: {
          submitText: '查询'
        },
        render: (_, dom) => dom.pop(),
        submitButtonProps: {
          style: {
            position: 'absolute',
            right: 0
          }
        }
      }} onFinish={async values => {
        console.log(values);
        requestCData(values);
        return true;
      }}>
                <ProFormGroup>
                  <ProFormDatePicker.Month name='beginDate' label='开始月份' width='sm' />
                  <ProFormDatePicker.Month name='endDate' label='结束月份' width='sm' />
                  <ProFormSelect name='dealerId' label='所属客户' placeholder='请选择客户' width='sm' request={dealerJsonData} />
                  <ProFormSelect name='salesId' label='所属销售' placeholder='请选择销售' width='sm' request={salesJsonData} />
                  <ProFormSelect name='product_name' label='产品名称' placeholder='请选择产品名称' width='sm' options={proData} fieldProps={{
            onSelect: (a, b: any) => {
              if (b) {
                setSubProData(b.children);
              } else {
                setSubProData([]);
              }
            }
          }}/>
                  <ProFormSelect name='product_standard' label='产品型号' placeholder='请选择产品型号' width='sm' options={subProData}/>
                </ProFormGroup>
              </ProForm>
              <div style={{
        height: 400
      }} >
                {
          /* <ColumnChart {...config}/> */
        }
              </div>
              {
        /* <Button type='primary' style={{marginTop:20}} name='export'><FileExcelOutlined />导出</Button> */
      }
        </Drawer>
        <Spin spinning={spinningFlag} style={{
      transform: 'translate(-50%,-50%)',
      left: '50%',
      top: '50%',
      position: 'absolute'
    }} />
    </PageContainer>;
};

export default PutOut;